package com.vf.cloud.paas.app.master.api.scene.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.vf.cloud.paas.app.master.api.scene.service.ISceneClassify;
import com.vf.cloud.paas.app.master.common.domain.Scene;
import com.vf.cloud.paas.app.master.common.domain.SceneClassify;
import com.vf.cloud.paas.app.master.common.domain.User;

@Service
public class SceneClassifyImpl implements ISceneClassify {

	public List<SceneClassify> getChildrens(SceneClassify param) {
		if (!StrKit.isBlank(param.getName())) {
			String sql = "SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM " + SceneClassify.TABLE_NAME
					+ " WHERE PID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS leaf  FROM " + SceneClassify.TABLE_NAME
					+ "  T WHERE T.PID=?  and t.name like '%" + param.getName() + "%'   ORDER BY T.SORT ASC";
			return SceneClassify.dao.find(sql, param.getPid());
		} else {
			String sql = "SELECT T.*, (CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM " + SceneClassify.TABLE_NAME
					+ " WHERE PID=T.ID)>0 THEN TRUE ELSE  FALSE END ) AS leaf  FROM " + SceneClassify.TABLE_NAME
					+ "  T WHERE T.PID=?    ORDER BY T.SORT ASC";
			return SceneClassify.dao.find(sql, param.getPid());
		}
	}

	public List<SceneClassify> getChildren(SceneClassify param,User user) {
		
		if(user==null) {
			List<SceneClassify> ProjectClassifys = SceneClassify.dao
					.find("select * from " + SceneClassify.TABLE_NAME + " where pid=? ", param.getId());
			for (SceneClassify p : ProjectClassifys) {
				p.setChildren(getChildren(p,user));
			}
			return ProjectClassifys;
		}else {
			List<SceneClassify> ProjectClassifys = SceneClassify.dao
					.find("select * from " + SceneClassify.TABLE_NAME + " where pid=? and create_user_id=? ", param.getId(),user.getId());
			for (SceneClassify p : ProjectClassifys) {
				p.setChildren(getChildren(p,user));
			}
			return ProjectClassifys;
		}
		

	}

	@Override
	public void delete(String id) {
		deleteChildrens(id);
	}

	public void deleteChildrens(String id) {
		List<SceneClassify> projectClassifys = SceneClassify.dao
				.find("select id from " + SceneClassify.TABLE_NAME + " where pid=? ", id);
		for (SceneClassify classify : projectClassifys) {
			if (classify.delete()) {
				deleteChildrens(classify.getId());
				Db.delete("delete From " + Scene.TABLE_NAME + " where classify_id=? ", classify.getId());
			}
		}
		// Db.delete("delete from master_user_project where project_id in (select id
		// from "+Project.TABLE_NAME+" where classify_id=? ) ",id);
		// Db.delete("delete from api_test_custom where project_id in (select id from
		// "+Project.TABLE_NAME+" where classify_id=? ) ",id);
		// Db.delete("delete From "+Project.TABLE_NAME+" where classify_id=? ",id);
		SceneClassify.dao.deleteById(id);
	}

}
